<template>
    <ul class="treeNode-ul">
        <li class="treeNode-li">
            <!-- 收起、展开 -->
            <span class="tree-expand" @click="handleExpand">
                <span v-if="data.children && data.children.length && !data.expand">+</span>
                <span v-if="data.children && data.children.length && data.expand">-</span>
            </span>
            <!-- 选择框 -->
            <dj-checkbox v-if="showCheckbox" v-model="data.checked" @change="handleCheck"></dj-checkbox>
            <!-- 标题 -->
            <span>{{data.title}}</span>
            <!-- 递归调用tree-node -->
            <div class="treeNode-box" v-if="data.expand">
                <dj-tree-node v-for="(item,index) in data.children" :key="index" :data="item" :show-checkbox="showCheckbox"></dj-tree-node>
            </div>
        </li>
    </ul>
</template>
<script>
import { findComponentUpWard } from '../../assets/js/findComponent.js'
import DjCheckbox from '../../components/Checkbox/Checkbox.vue'
export default {
  name: 'dj-tree-node',
  components: { DjCheckbox },
  props: {
    data: {
      type: Object,
      required: true
    },
    showCheckbox: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {}
  },
  computed: {
    tree () {
      let res = findComponentUpWard(this, 'dj-tree')
      return res
    }
  },
  watch: {
    'data.children': {
      handler (data) {
        if (data) {
          const checkedAll = !data.some(item => !item.checked)
          this.$set(this.data, 'checked', checkedAll)
        }
      },
      deep: true
    }
  },
  methods: {
    handleExpand () {
      this.$set(this.data, 'expand', !this.data.expand)

      if (this.tree) {
        this.tree.emitEvent('on-toggle-expand', this.data)
      }
    },
    handleCheck (checked) {
      this.updateTreeDown(this.data, checked)
    },
    updateTreeDown (data, checked) {
      this.$set(data, 'checked', checked)

      if (data.children && data.children.length) {
        data.children.forEach(item => {
          this.updateTreeDown(item, checked)
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
    .treeNode-ul{
        list-style: none;
        padding-left: 10px;
        .treeNode-li{
            list-style: none;
            padding-left: 10px;
            .tree-expand{
                cursor: pointer;
                margin-right: 5px;
                span{
                    font-weight: bold;
                }
            }
        }
    }
</style>
